package com.besall.allbase.view.activity.chipstoollevel4.checkcrc;

import static com.bes.bessdk.service.checkcrc.CheckCrcConstants.OP_TOTA_CHECK_CRC_DATA;
//import static com.besall.allbase.bluetooth.BluetoothConstants.Scan.BES_SCAN_RESULT;


import android.Manifest;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.bes.bessdk.BesSdkConstants;
import com.bes.bessdk.scan.BtHeleper;
import com.bes.bessdk.service.base.BesServiceConfig;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.bessdk.utils.SPHelper;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.utils.DeviceProtocol;
//import bb.lanxing.R;

import com.besall.allbase.bluetooth.BluetoothConstants;
import com.besall.allbase.common.utils.ActivityUtils;
import com.besall.allbase.view.base.BaseActivity;

import bb.lanxing.R;

/**
 * @author ericshen
 * @time $ $
 */
public class CheckCrcActivity extends BaseActivity<ICheckCrcActivity, CheckCrcPresenter> implements ICheckCrcActivity, BesServiceListener, View.OnClickListener {
    public static CheckCrcActivity instance;
    public String cur_title = "Check CRC";

    private Button pick_device;
    private Button pick_device_ble;
    private Button connect_device;
    private TextView device_address;
    private TextView device_name;

    private Button get_crc;
    private TextView show_crc;
    private Button factory_reset;

    BluetoothDevice mDevice;
    HmDevice mHmDevice;
    BesServiceConfig mServiceConfig;

    @Override
    protected CheckCrcPresenter createPresenter() {
        return new CheckCrcPresenter();
    }

    @Override
    protected void initBeforeSetContent() {
        mServiceConfig = new BesServiceConfig();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.act_connect;
    }

    @Override
    protected void bindView() {
        pick_device = (Button) findViewById(R.id.pick_device_connect);
        pick_device_ble = (Button) findViewById(R.id.pick_device_ble);
        connect_device = (Button) findViewById(R.id.connect_device_connect);
        device_address = (TextView) findViewById(R.id.device_address_connect);
        device_name = (TextView) findViewById(R.id.device_name);

        loadanimdrawable();
    }

    @Override
    protected void initView() {
        inittoolbar(cur_title);
        pick_device.setOnClickListener(instance);
        pick_device_ble.setOnClickListener(instance);
        pick_device_ble.setVisibility(View.VISIBLE);
        connect_device.setOnClickListener(instance);
    }

    @Override
    protected void setInstance() {
        instance = this;
    }

    @Override
    protected void removeInstance() {
        instance = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BluetoothConstants.Scan.REQUEST_CODE_SCAN) {
            onPickDevice(resultCode, data);
        }
    }

    private void onPickDevice(int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            mHmDevice = (HmDevice) data.getSerializableExtra(BluetoothConstants.Scan.BES_SCAN_RESULT);
            mDevice = BtHeleper.getBluetoothAdapter(instance).getRemoteDevice(mHmDevice.getPreferredProtocol() == DeviceProtocol.PROTOCOL_BLE ? mHmDevice.getBleAddress() : mHmDevice.getDeviceMAC());
            device_address.setText(mDevice.getAddress());
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            device_name.setText(mDevice.getName());
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            finish();
        }
/*        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }*/
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.pick_device_connect){
            mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_SPP);
            mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_SPP);
        }else if(v.getId() == R.id.pick_device_ble){
            mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_BLE);
            mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_BLE);
        }else if(v.getId() == R.id.connect_device_connect){
            loadinganim();
            if (mHmDevice == null) {
                loadingDialog.dismiss();
                ActivityUtils.showToast(R.string.connect_failed);
                return;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mServiceConfig.getDeviceProtocol() == DeviceProtocol.PROTOCOL_BLE) {
                        mServiceConfig.setServiceUUID(BesSdkConstants.BES_TOTA_SERVICE_OTA_UUID);
                        mServiceConfig.setCharacteristicsUUID(BesSdkConstants.BES_TOTA_CHARACTERISTI_OTA_UUID);
                        mServiceConfig.setDescriptorUUID(BesSdkConstants.BES_TOTA_DESCRIPTOR_OTA_UUID);
                    } else if (mServiceConfig.getDeviceProtocol() == DeviceProtocol.PROTOCOL_SPP) {
                        mServiceConfig.setServiceUUID(BesSdkConstants.BES_SPP_CONNECT);
                    }
                    mServiceConfig.setDevice(mHmDevice);
                    mServiceConfig.setTotaConnect(true);
                    boolean useTotaV2 = (boolean) SPHelper.getPreference(instance, BesSdkConstants.BES_TOTA_USE_TOTAV2, BesSdkConstants.BES_TOTA_USE_TOTAV2_VALUE);
                    mServiceConfig.setUseTotaV2(useTotaV2);
                    mPresenter.connectDevice(mServiceConfig, instance, instance);
                }
            });
        }else if(v.getId() == R.id.get_crc_connect){
            mPresenter.getCrc();
        }else if(v.getId() == R.id.factory_reset_connect){
            mPresenter.factoryReset();
        }
/*  origin code
        switch (v.getId()) {
            case R.id.pick_device_connect:
                mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_SPP);
                mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_SPP);
                break;
            case R.id.pick_device_ble:
                mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_BLE);
                mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_BLE);
                break;
            case R.id.connect_device_connect:
                loadinganim();
                if (mHmDevice == null) {
                    loadingDialog.dismiss();
                    ActivityUtils.showToast(R.string.connect_failed);
                    return;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mServiceConfig.getDeviceProtocol() == DeviceProtocol.PROTOCOL_BLE) {
                            mServiceConfig.setServiceUUID(BesSdkConstants.BES_TOTA_SERVICE_OTA_UUID);
                            mServiceConfig.setCharacteristicsUUID(BesSdkConstants.BES_TOTA_CHARACTERISTI_OTA_UUID);
                            mServiceConfig.setDescriptorUUID(BesSdkConstants.BES_TOTA_DESCRIPTOR_OTA_UUID);
                        } else if (mServiceConfig.getDeviceProtocol() == DeviceProtocol.PROTOCOL_SPP) {
                            mServiceConfig.setServiceUUID(BesSdkConstants.BES_SPP_CONNECT);
                        }
                        mServiceConfig.setDevice(mHmDevice);
                        mServiceConfig.setTotaConnect(true);
                        boolean useTotaV2 = (boolean) SPHelper.getPreference(instance, BesSdkConstants.BES_TOTA_USE_TOTAV2, BesSdkConstants.BES_TOTA_USE_TOTAV2_VALUE);
                        mServiceConfig.setUseTotaV2(useTotaV2);
                        mPresenter.connectDevice(mServiceConfig, instance, instance);
                    }
                });
                break;
            case R.id.get_crc_connect:
                mPresenter.getCrc();
                break;
            case R.id.factory_reset_connect:
                mPresenter.factoryReset();
                break;
            default:
                break;
        }*/
    }

    @Override
    public void onTotaConnectState(boolean state, HmDevice hmDevice) {
        if (!state) {
            Toast.makeText(instance, R.string.connect_failed,Toast.LENGTH_LONG).show();
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (state == true) {
                    initlayout();
                    loadingDialog.dismiss();
                }

            }
        });
    }

    @Override
    public void onErrorMessage(int msg, HmDevice hmDevice) {
        Toast.makeText(instance, R.string.connect_failed,Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
        if (msg == OP_TOTA_CHECK_CRC_DATA) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    show_crc.setText(msgStr);
                }
            });
        }
    }

    @Override
    public void onSuccessMessage(int msg, HmDevice hmDevice) {

    }

    public void initlayout() {
        setContentView(R.layout.activity_checkcrc);
        inittoolbar(cur_title);
        get_crc = (Button)findViewById(R.id.get_crc_connect);
        get_crc.setOnClickListener(instance);
        show_crc = (TextView)findViewById(R.id.show_crc);
        factory_reset = (Button)findViewById(R.id.factory_reset_connect);
        factory_reset.setOnClickListener(instance);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
